﻿using FarmSmartSleep.Common.Domain;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;
using System.Collections.Generic;

namespace FarmSmartSleep.Organ.API.Application.Commands.CottagesCommands
{
    public class FieldSearchHander : IRequestHandler<FieldSearchCommand, ResultPage<Fields>>
    {

        private readonly IBaseRepository<Fields> fieldsRepository;
        private readonly ILogger<FieldSearchHander> logger;

        public FieldSearchHander(IBaseRepository<Fields> fieldsRepository, ILogger<FieldSearchHander> logger)
        {
            this.fieldsRepository = fieldsRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 获取栋舍下栏位信息
        /// </summary>
        /// <param name="request">获取栋舍下栏位信息请求对象</param>
        /// <param name="cancellationToken"></param>
        /// <returns>获取栋舍下栏位信息响应对象</returns>
        public async Task<ResultPage<Fields>> Handle(FieldSearchCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new ResultPage<Fields>();
                var list = fieldsRepository.GetAll().ToList();
                if (request.CottagesId != 0)
                {
                    list = list.Where(c => c.CottageId == request.CottagesId).ToList();
                }

                if (request.PageIndex != 0)
                {

                    result.totalCount = list.Count;
                    result.totalPage = (int)Math.Ceiling((result.totalCount) * 1.0 / request.PageSize);
                    result.Data = list.OrderBy(c => c.FieIdId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                }
                else
                {
                    result.Data = list;
                }

                logger.LogInformation("获取栋舍下栏位信息方法调用成功");
                return result;




            }
            catch (Exception ex)
            {
                logger.LogError("获取栋舍下栏位信息方法调用出错" + ex);
                throw;
            }
        }
    }
}
